import React from 'react';
import { Form, Input, Button, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { userApi } from '@/api';
import { useTranslation } from 'react-i18next';
import { useAppStore } from '@/stores';
import './style.css';

interface LoginFormData {
    username: string;
    password: string;
}

export const Login: React.FC = () => {
    const { t } = useTranslation();
    const navigate = useNavigate();
    const [form] = Form.useForm();
    const { setAuth } = useAppStore();

    const onFinish = async (values: LoginFormData) => {
        try {
            const { data } = await userApi.login(values);
            setAuth(data);
            message.success(t('auth.loginSuccess'));
            navigate('/');
        } catch (error) {
            message.error(t('auth.loginError'));
        }
    };

    return (
        <div className="login-wrapper">
            <div className="login-form">
                <h2 className="login-title">
                    {t('auth.loginTitle')}
                </h2>
                <Form
                    form={form}
                    layout="vertical"
                    onFinish={onFinish}
                >
                    <Form.Item
                        name="username"
                        label={t('auth.username')}
                        rules={[{ required: true, message: t('auth.usernameRequired') }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="password"
                        label={t('auth.password')}
                        rules={[{ required: true, message: t('auth.passwordRequired') }]}
                    >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" block>
                            {t('auth.login')}
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    );
};

export default Login;